package com.sfh.gd.controller;

import cn.binarywang.wx.miniapp.api.WxMaService;
import cn.binarywang.wx.miniapp.bean.WxMaJscode2SessionResult;
import cn.binarywang.wx.miniapp.bean.WxMaPhoneNumberInfo;
import cn.binarywang.wx.miniapp.bean.WxMaUserInfo;
import cn.binarywang.wx.miniapp.util.WxMaConfigHolder;
import cn.dev33.satoken.util.SaResult;
import com.sfh.gd.common.Log;
import com.sfh.gd.common.enums.BusinessType;
import com.sfh.gd.common.enums.OperatorType;
import com.sfh.gd.domain.dto.GetPhoneDTO;
import com.sfh.gd.domain.dto.LoginWxDTO;
import com.sfh.gd.domain.dto.SignInDTO;
import com.sfh.gd.service.MemberService;
import lombok.RequiredArgsConstructor;
import me.chanjar.weixin.common.error.WxErrorException;
import org.apache.commons.lang3.StringUtils;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

/**
 * 微信用户接口
 */
@RestController
@RequestMapping("/api/user")
@RequiredArgsConstructor
public class APIWxUserController {

    private final WxMaService wxMaService;
    private final MemberService memberService;
    /**
     * 注册接口
     */
    @PostMapping("/signIn")
    public SaResult signIn(@RequestBody @Validated SignInDTO signInDTO) {

        return memberService.signIn(signInDTO);
    }

    /**
     * 登陆接口
     */
    @PostMapping("/login")
    public SaResult login(@RequestBody @Validated LoginWxDTO loginVo) {

        return memberService.login(loginVo);
    }

    /**
     * 获取用户基础信息
     */
    @Log(title = "获取用户基础信息", businessType = BusinessType.OTHER, operatorType = OperatorType.WECHAT)
    @GetMapping("getUserInfo")
    public SaResult getUserInfo(){
        return memberService.getUserInfo();
    }

    /**
     * 获取openid
     */
    @Log(title = "获取openid", businessType = BusinessType.OTHER, operatorType = OperatorType.WECHAT)
    @GetMapping("getOpenid")
    public SaResult getOpenid(@RequestBody LoginWxDTO loginVo){
        if (StringUtils.isBlank(loginVo.getCode())) {
            return SaResult.error("appid不能为空！");
        }

        if (!wxMaService.switchover(loginVo.getAppid())) {
            throw new IllegalArgumentException(String.format("未找到对应appid=[%s]的配置，请核实！", loginVo.getAppid()));
        }
        WxMaJscode2SessionResult session;
        try {
            session = wxMaService.getUserService().getSessionInfo(loginVo.getCode());
            return SaResult.data(session);
        } catch (WxErrorException e) {
            //log.error(e.getMessage(), e);
        } finally {
            WxMaConfigHolder.remove();//清理ThreadLocal
        }
        return SaResult.error();
    }

    /**
     * 获取用户信息接口
     */
    @Log(title = "获取用户信息", businessType = BusinessType.OTHER, operatorType = OperatorType.WECHAT)
    @GetMapping("/info")
    public SaResult info(@PathVariable String appid, String sessionKey,
                         String signature, String rawData, String encryptedData, String iv) throws WxErrorException {
        if (!wxMaService.switchover(appid)) {
            throw new IllegalArgumentException(String.format("未找到对应appid=[%s]的配置，请核实！", appid));
        }

        // 用户信息校验
        if (!wxMaService.getUserService().checkUserInfo(sessionKey, rawData, signature)) {
            WxMaConfigHolder.remove();//清理ThreadLocal
            return SaResult.error("user check failed");
        }

        // 解密用户信息
        WxMaUserInfo userInfo = wxMaService.getUserService().getUserInfo(sessionKey, encryptedData, iv);
        WxMaConfigHolder.remove();//清理ThreadLocal
        return SaResult.data(userInfo);
    }

    /**
     * 获取用户绑定手机号信息
     */
    @Log(title = "获取用户绑定手机号信息", businessType = BusinessType.OTHER, operatorType = OperatorType.WECHAT)
    @PostMapping("/phone")
    public SaResult phone(@RequestBody GetPhoneDTO dto) throws WxErrorException {

        // 解密
        WxMaPhoneNumberInfo phoneNoInfo = wxMaService.getUserService().getPhoneNoInfo(dto.getCode());
        WxMaConfigHolder.remove();//清理ThreadLocal
        return SaResult.data(phoneNoInfo);
    }
}
